var util = require("../../utils/util.js");
// pages/order/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: '',
    cartList: '',
    totalPrice: '0',
    shippingPrice: '4',
    systemCfg: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      // 如果没有收货地址，则从服务器拉取一个
      this.getCartList()
      this.getAddress()
      this.getSystemCfg()
  },
  getSystemCfg: function () {
    var cfg = wx.getStorageSync('cfg')
    var _this = this
    if (!cfg) {
      util.djax({
        url: '/wxapp/other/cfg'
      }).then(function (res) {
        cfg = res.data
        wx.setStorageSync('cfg', res.data)
      })
    }

    var cartList = wx.getStorageSync('wantBuy')
    var totalMoney = 0
    for (var i = 0; i < cartList.length; i++) {
      totalMoney += cartList[i].price * cartList[i].number
    }
    this.setData({
      systemCfg: cfg,
      totalMoney: totalMoney
    })
  },
  getCartList: function() {
    var cartList = wx.getStorageSync('wantBuy')
    if (!cartList) {
      wx.reLaunch({
        url: '/pages/index/index',
      })
    }
    this.setData({
      cartList: cartList
    })
  },
  goSelAddr: function() {
    wx.navigateTo({
      url: '/pages/address/index',
    })
    wx.setStorageSync('fromWhere','/pages/order/index')
  },
  getAddress: function() {
    var address = wx.getStorageSync('orderAddress')
    var _this = this
    if (!address) {
        util.djax({
          url: '/wxapp/Address/index'
        }).then(function(res){
            
            if (res.data.length==0) {
                // 跳转去添加地址
               _this.goSelAddr()
            } else {
              wx.setStorageSync('orderAddress', res.data[0])
              _this.setData({
                address: res.data[0]
              })
              _this.calcMoney()
            }

        })
     } else {
       this.setData({
         address: address
       })
      this.calcMoney()
     }
  },
  calcMoney: function() {
      var cartList = this.data.cartList, address = this.data.address;
      var _this = this;
      util.djax({
        url: '/wxapp/Address/Elevator'
      }).then(function(res) {
        var shippingPirce = '';
        for (var i=0;i<res.data.length; i++) {
          if (res.data[i].id == address.elevator_id) {
            shippingPirce = res.data[i].price
          }
        }
        var systemCfg = wx.getStorageSync('cfg')
        if (shippingPirce == '') {
          shippingPirce = systemCfg[6].value
        }
        var totalMoney = parseFloat(shippingPirce);
        totalMoney = totalMoney ? totalMoney:0;
        for (var i = 0; i < cartList.length;i++) {
          totalMoney += parseFloat(cartList[i].price) * cartList[i].number
        }
        
        _this.setData({
          shippingPrice: shippingPirce,
          totalPrice: totalMoney
        })
      
      })

  },
  submitOrder: function(e) {
    var _this = this
    var address = wx.getStorageSync('orderAddress')
    var totalprice = e.currentTarget.dataset.total
    if (!address) {
      wx.showToast({
        title: '请选择地址！',
        icon: 'none'
      })
    }

    var cartList = wx.getStorageSync('wantBuy')
    if (!cartList) {
        // 跳转回购物车
    
    } else {
      var cartId = [];
      for (var i=0; i<cartList.length; i++) {
        cartId.push(cartList[i].id)
      }
      util.djax({
        url: '/wxapp/Order/pay',
        data: {
          a: address.id,
          b: cartId.join(','),
          totalprice: totalprice
        }
      }).then(function(res) {
        if (res.code!=1001) {
          wx.showToast({
            title: res.msg,
            icon: 'none'
          })
          return false;
        }
        var data = res.data
        wx.requestPayment({
          'timeStamp': data.timeStamp.toString(),
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': 'MD5',
          'paySign': data.paysign,
          'success': function (res) {
            // 成功则删除购物车
            console.log(cartId)
            util.djax({
              url: '/wxapp/Order/delCart',
              data: {
                b: cartId.join(',')
              }
            }).then(function(res){
              // 清空本地存储的下单信息
              wx.setStorageSync('wantBuy',null)
              // 跳转到我的订单
              wx.reLaunch({
                url: '/pages/myorder/index',
              })
            })
          },
          'fail': function (res) {
            wx.showToast({
              title: '取消支付！',
              icon: 'none'
            })
            // 取消支付，则删除订单
            util.djax({
              url: '/wxapp/Order/del',
              data: {
                id: data.id
              }
            })
          }
        })
      })

    }


  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  }
})